package com.tianxiao.faas.common.util;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class GeoUtils {

    private static final double EarthRadius = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    public static double getDistance(Double fLa, Double fLo,
                                     Double sLa, Double sLo) {
        if (fLa == null || fLo == null || sLa == null || sLo == null) {
            return 0d;
        }
        double firstRadLat = rad(fLa);
        double firstRadLng = rad(fLo);
        double secondRadLat = rad(sLa);
        double secondRadLng = rad(sLo);
        double a = firstRadLat - secondRadLat;
        double b = firstRadLng - secondRadLng;
        double cal = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(firstRadLat)*Math.cos(secondRadLat) * Math.pow(Math.sin(b / 2),2))) * EarthRadius;
        double result = Math.round(cal * 10000d);

        return result;
    }

    public static String getDistanceStr(Double fLa, Double fLo,
                                        Double sLa, Double sLo) {
        double distance = getDistance(fLa, fLo, sLa, sLo);
        if (0d == distance) {
            return "";
        }
        double km = distance / 10000;
        if (km >= 1) {
            BigDecimal bigDecimal = new BigDecimal(km);
            bigDecimal = bigDecimal.setScale(2, RoundingMode.HALF_UP);
            return bigDecimal.toString() + "km";
        } else {
            return distance + "m";
        }
    }

    public static void main(String[] args) {
        long currentTimeMillis = System.currentTimeMillis();
        double la = 30.264776, lo = 119.92914;
        double la2 = 30.304694, lo2 =  119.99583;

        double distance = getDistance(la, lo, la2, lo2);
        System.out.println(distance);
        System.out.println(System.currentTimeMillis() - currentTimeMillis);
    }
}
